package com.bluesky.framework.config.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.bluesky.common.exception.CustomException;
import com.bluesky.common.result.ResultCode;
import com.bluesky.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MP注入处理器
 *
 * @author Kevin
 */
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {

    public static final String CREATED_TIME = "createdTime";
    public static final String UPDATED_TIME = "updatedTime";

    public static final String CREATED_BY = "createdBy";
    public static final String UPDATED_BY = "updatedBy";

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            if (metaObject.hasGetter(CREATED_TIME)) {
                if (metaObject.getValue(CREATED_TIME) == null) {
                    this.strictInsertFill(metaObject, CREATED_TIME, Date.class, new Date());
                }
            }
            if (metaObject.hasGetter(CREATED_BY)) {
                if (metaObject.getValue(CREATED_BY) == null) {
                    this.strictInsertFill(metaObject, CREATED_BY, String.class, SecurityUtils.getLoginUser().getSysUser().getId().toString());
                }
            }
            if (metaObject.hasGetter(UPDATED_TIME)) {
                if (metaObject.getValue(UPDATED_TIME) == null) {
                    this.strictUpdateFill(metaObject, UPDATED_TIME, Date.class, new Date());
                }
            }
            if (metaObject.hasGetter(UPDATED_BY)) {
                if (metaObject.getValue(UPDATED_BY) == null) {
                    this.strictUpdateFill(metaObject, UPDATED_BY, String.class, SecurityUtils.getLoginUser().getSysUser().getId().toString());
                }
            }
        } catch (Exception e) {
            throw new CustomException(ResultCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (metaObject.hasGetter(UPDATED_TIME)) {
                if (metaObject.getValue(UPDATED_TIME) == null) {
                    this.strictUpdateFill(metaObject, UPDATED_TIME, Date.class, new Date());
                }
            }
            if (metaObject.hasGetter(UPDATED_BY)) {
                if (metaObject.getValue(UPDATED_BY) == null) {
                    this.strictUpdateFill(metaObject, UPDATED_BY, String.class, SecurityUtils.getLoginUser().getSysUser().getId().toString());
                }
            }
        } catch (Exception e) {
            throw new CustomException(ResultCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

}
